package com.isoftstone.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.isoftstone.mapper.DormitoryMapper;
import com.isoftstone.pojo.Dormitory;
import com.isoftstone.service.DormitoryService;
import com.isoftstone.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author :W.
 * @Date:2025/9/14 16:36
 */

/**
 * 业务逻辑接口实现类
 */
@Service
public class DormitoryServiceImpl implements DormitoryService {
    @Autowired
    private DormitoryMapper dormitoryMapper;

    // 查询所有宿舍
    @Override
    public Result<List<Dormitory>> findAll() {
        List<Dormitory> dormitories = dormitoryMapper.findAll();
        return Result.success(dormitories);
    }

    // 分页查询
    @Override
    public Result<PageInfo<Dormitory>> findByPage(int pageNum, int pageSize, String building_number, String room_number, Integer capacity) {
        // 使用严格的PageHelper.startPage方式
        Page<Object> page = PageHelper.startPage(pageNum, pageSize, true);
        List<Dormitory> dormitories = dormitoryMapper.findByPage(building_number, room_number, capacity);
        // 打印实际执行的SQL
        System.out.println("实际执行的SQL: " + page.toString());

        PageInfo<Dormitory> pageInfo = new PageInfo<>(dormitories);
        return Result.success(pageInfo);
    }

    // 根据ID查询宿舍
    @Override
    public Result<Dormitory> findById(Integer id) {
        Dormitory dormitory = dormitoryMapper.findById(id);
        if (dormitory != null) {
            return Result.success(dormitory);
        } else {
            return Result.error("未找到ID为" + id + "的宿舍");
        }
    }

    // 新增宿舍
    @Override
    public Result<?> addDormitory(Dormitory dormitory) {
        // 新增时设置初始入住人数为0
        if (dormitory.getCurrentOccupancy() == null) {
            dormitory.setCurrentOccupancy(0);
        }
        boolean success = dormitoryMapper.addDormitory(dormitory) > 0;
        return success ? Result.success(true) : Result.error("新增宿舍失败");
    }

    // 更新宿舍信息
    @Override
    @Transactional
    public Result<?> updateDormitory(Dormitory dormitory) {
        // 1. 先查询当前宿舍的最新数据（确保获取到真实的当前入住人数）
        Dormitory existingDorm = dormitoryMapper.findById(dormitory.getDormitoryId());
        if (existingDorm == null) {
            return Result.error("更新失败：未找到该宿舍");
        }
        // 2. 核心校验：编辑后的可住人数 ≥ 当前入住人数
        Integer newCapacity = dormitory.getCapacity(); // 编辑后提交的可住人数
        Integer currentOccupancy = existingDorm.getCurrentOccupancy(); // 数据库中真实的入住人数
        if (newCapacity != null && newCapacity < currentOccupancy) {
            return Result.error(
                    String.format("更新失败：可住人数不能小于当前入住人数（当前入住%d人，最小可住人数为%d）",
                            currentOccupancy, currentOccupancy)
            );
        }
        // 3. 校验通过，执行更新操作
        boolean success = dormitoryMapper.updateDormitory(dormitory) > 0;
        return success ? Result.success("宿舍信息更新成功") : Result.error("更新宿舍信息失败");
    }

    // 删除宿舍
    @Override
    @Transactional
    public Result<?> deleteDormitory(Integer id) {
        boolean success = dormitoryMapper.deleteDormitory(id) > 0;
        return success ? Result.success(true) : Result.error("删除宿舍失败，宿舍不存在");
    }

    // 查询有空位的宿舍
    @Override
    public Result<List<Dormitory>> selectAvailable() {
        List<Dormitory> dormitories = dormitoryMapper.selectAvailable();
        return Result.success(dormitories);
    }

    @Override
    @Transactional
    public Result<?> batchDeleteDorms(List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return Result.error("请选择要删除的宿舍");
        }
        int deleteCount = dormitoryMapper.batchDeleteDorms(ids);
        if (deleteCount > 0) {
            return Result.success("批量删除成功，共删除 " + deleteCount + " 条数据");
        } else {
            return Result.error("批量删除失败，未找到对应宿舍");
        }
    }
    // 更新宿舍入住人数（添加事务控制）
    @Override
    @Transactional
    public Result<?> updateOccupancy(Integer dormitoryId, Integer newOccupancy) {
        // 校验参数
        if (dormitoryId == null || newOccupancy == null) {
            return Result.error("参数错误：宿舍ID和新入住人数不能为空");
        }

        // 校验宿舍存在
        Dormitory dorm = dormitoryMapper.findById(dormitoryId);
        if (dorm == null) {
            return Result.error("宿舍不存在");
        }

        // 校验新人数合法性（0 <= 新人数 <= 可住人数）
        if (newOccupancy < 0 || newOccupancy > dorm.getCapacity()) {
            return Result.error("入住人数超出范围（0-" + dorm.getCapacity() + "）");
        }

        // 执行更新
        int rows = dormitoryMapper.updateOccupancy(dormitoryId, newOccupancy);
        return rows > 0 ? Result.success("入住人数更新成功") : Result.error("入住人数更新失败");
    }

    // 新增实现：根据ID查询宿舍
    @Override
    public Result<Dormitory> getDormitoryById(Integer dormitoryId) {
        if (dormitoryId == null) {
            return Result.error("宿舍ID不能为空");
        }
        Dormitory dormitory = dormitoryMapper.findById(dormitoryId);
        if (dormitory == null) {
            return Result.error("未找到对应宿舍信息");
        }
        return Result.success(dormitory);
    }
}
